package com.atguigu.compare;
import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;

/*Comparator接口的使用
1.重写compare(Object o1,Object o2)方法，比较o1和o2的大小:如果返回正整数，则表示o1>o2;
//如果返回负整数，则o1<o2  ;返回0则o1==o2
* */
public class CompareTest2 {
    @Test
    public void test(){
        String[] arr=new String[]{"AA","CC","MM","GG","JJ","DD","KK"};
        Arrays.sort(arr, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                if(o1 instanceof String&&o2 instanceof String){
                    String s1=(String)o1;
                    String s2=(String)o2;
                    return -s1.compareTo(s2);
                }
                throw new RuntimeException("输入的数据类型不一致");
            }
        });
    }
    @Test
    public void test2(){
        Goods[] goods=new Goods[4];
        goods[0]=new Goods("lenovoMouse",34);
        goods[1]=new Goods("dellMouse",43);
        goods[2]=new Goods("xiaomiMouse",12);
        goods[3]=new Goods("huaweiMouse",65);
        Arrays.sort(goods, new Comparator<Goods>() {
            @Override
            //指明产品比较大小的方式:按照名称从低到高，再按照价格从高到低排序
            public int compare(Goods o1, Goods o2) {
                if(o1.getName().equals(o2.getName())){
                    if(o1.getPrice()>o2.getPrice()){
                        return 1;
                    }else if(o1.getPrice()<o2.getPrice()){
                        return -1;
                    }else{
                        return 0;
                    }
                }else{
                    return o1.getName().compareTo(o2.getName());
                }
            }
        });
        System.out.println(Arrays.toString(goods));
    }
}
